import java.util.ArrayList;
import java.awt.event.*;
import java.io.*;

/**
 * EBook Organizer
 * 4/30/2010
 * <P>
 * The Main model for the <code>EBookOrganizer</code>.
 * </P>
 * @version 0.1
 */
public class OrganizerModel extends Organizer implements java.io.Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 815692034636227802L;
	private ArrayList<ActionListener> actionListenerList;
	
	public OrganizerModel () {
		super();
		
		//init if there is a default File
		File file = new File( super.getSettingsModel().filePath );
		if (file!=null) {
			load(file);
		}
	}
	
	public void addFolder(Folder folder) {
		super.addFolder(folder);
		processEvent(
				new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "add folder") );
	}
	
	public void clearFolders() {
		super.clearFolders();
		processEvent(
				new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "clear folders") );
	}
	
	public void removeFolder(Folder folder) {
		super.removeFolder(folder);
		processEvent(
				new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "remove folder") );
	}
	
	public void load(File file) {
		super.load(file);
		processEvent(
				new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "load") );
	}
	
	public void save( File file ) {
		super.save(file);
		processEvent(
				new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "save") );
	}
	
	public synchronized void addActionListener(ActionListener l) {
		if (actionListenerList == null) {
			actionListenerList = new ArrayList<ActionListener>();
		}
		
		actionListenerList.add(l);
	}
	
	public synchronized void removeActionListener(ActionListener l) {
		if (actionListenerList != null && actionListenerList.contains(l))
			actionListenerList.remove(l);
	}
	
	@SuppressWarnings("unchecked")
	public void processEvent(ActionEvent e) {
		ArrayList<ActionListener> list;
		
		synchronized(this) {
			if (actionListenerList == null) return;
			list = (ArrayList<ActionListener>)actionListenerList.clone();
		}
		
		for (int i = 0; i < list.size(); i++) {
			ActionListener listener = list.get(i);
			listener.actionPerformed(e);
		}
		
		System.out.println(e.paramString());	
		}
}
